import React from "react";
import { sleep } from 'antd-mobile/es/utils/sleep'
import styles from '@/assets/css/order.module.css'
import Menu from '@/views/common/menu'

export default () => {
    const [list, SetList] = useState<any>([])
    const [hasMore, SethasMore] = useState<boolean>(false)
    const [page, SetPage] = useState<number>(1)

    const [status, SetStatus] = useState<string>('all')

    let [form] = React.UI.Form.useForm()
    const [orderId, SetOrderId] = useState<number>(0)
    const [rateShow, SetRateShow] = useState<boolean>(false)
    const [comment] = useState<any>({rate: 0, content: ''})

    useEffect(() => {
        GetOrderList()
    }, [])

    // 检测tab切换触发的钩子函数
    useEffect(() => {
        OnRefresh()
    }, [status])

    // 获取订单列表
    const GetOrderList = async () => {
        let params = {
            busid: React.business.id,
            status: status,
            page: page
        }

        let result = await React.request.post('/order/OrderIndex', params)

        if(result.code == 0)
        {
            SethasMore(false)
            return false
        }

        SethasMore(true)
        SetPage(page + 1)
        SetList(list.concat(result.data))
    }

    // 下拉刷新
    const OnRefresh = async () => {
        SetPage(1)
        SethasMore(true)
        SetList([])

        await sleep(800)
        GetOrderList()
    }

    // 上拉加载
    const LoadMore = async () => {
        await sleep(800)
        GetOrderList()
    }

    // 状态
    const Status = (props: any) => {
        const order = props.status

        if(order.status == 1 || order.status == 4)
        {
            return (
                <React.UI.Tag color='#87d068' fill='outline'>{order.status_text}</React.UI.Tag>
            )
        }

        if(order.status == 2 || order.status == 3)
        {
            return (
                <React.UI.Tag color='#1677ff' fill='outline'>{order.status_text}</React.UI.Tag>
            )
        }

        if(order.status == -1 || order.status == -2)
        {
            return (
                <React.UI.Tag color='warning' fill='outline'>{order.status_text}</React.UI.Tag>
            )
        }

        if(order.status == -3)
        {
            return (
                <React.UI.Tag color='danger' fill='outline'>{order.status_text}</React.UI.Tag>
            )
        }
    }

    // 按钮组
    const ButtonList = (order: any) => {
        if(order.status == 1)
        {
            return (
                <React.UI.Button color='danger' size='small' onClick={() => ApplyRefund(order.id)}>申请退款</React.UI.Button>
            )
        }

        if(order.status == '3' && !order.rate)
        {
            return (
                <React.UI.Button color='success' size='small' onClick={() => ToComment(order.id)}>立即评价</React.UI.Button>
            )
        }

        if(order.status == '-1')
        {
            return (
                <React.UI.Button color='warning' size='small'>等待审核中...</React.UI.Button>
            )
        }
    }

    // 申请退款
    const ApplyRefund = async (orderid: number) => {
        let res = await React.UI.Dialog.confirm({
            title: '退款提醒',
            content: '是否确认申请退款'
        })

        if(!res) return false

        let params = {
            busid: React.business.id,
            orderid
        }

        let result = await React.request.post('/order/ApplyRefund', params)

        if(result.code == 0)
        {
            React.toast(result.msg, 'fail')
            return false
        }

        React.toast(result.msg, 'success', () => OnRefresh())
        return false
    }

    // 立即评价
    const ToComment = (orderId: number) => {
        SetOrderId(orderId)
        SetRateShow(true)
    }

    // 关闭评价弹层
    const ClosePopup = () => {
        SetRateShow(false)
        form.setFieldsValue({
            rate: 0,
            content: ''
        })
    }

    // 提交评价
    const Submit = async (values: any) => {
        SetRateShow(false)

        values.busid = React.business.id
        values.orderid = orderId

        let result = await React.request.post('/order/OrderRate', values)

        if(result.code == 0)
        {
            React.toast(result.msg, 'fail')
            return false
        }

        React.toast(result.msg, 'success', () => OnRefresh())
        return false
    }

    return (
        <>
            {/* 选项卡 */}
            <React.UI.Tabs activeKey={status} activeLineMode={'full'} onChange={(val:string) => SetStatus(val)}>
                <React.UI.Tabs.Tab title="全部" key="all" />
                <React.UI.Tabs.Tab title="已支付" key="1" />
                <React.UI.Tabs.Tab title="已入住" key="2" />
                <React.UI.Tabs.Tab title="已退房" key="3" />
                <React.UI.Tabs.Tab title="已评价" key="4" />
                <React.UI.Tabs.Tab title="售后" key="-1" />
            </React.UI.Tabs>

            <div className={styles.bodyList}>
                {/* 下拉刷新 */}
                <React.UI.PullToRefresh style={{paddingBottom: '50px'}} onRefresh={OnRefresh}>
                    {/* 订单列表 */}
                    <div className={styles.order_list}>
                        {list && list.map((item: any, key: number) => (
                            <div className={styles.item} key={key}>
                                <div className={styles.item_top}>
                                    <p>{item.room.name}</p>
                                    <div className={styles.top_tag}>
                                        <Status status={item} />
                                    </div>
                                </div>

                                <div className={styles.house}>
                                    <div className={styles.item_swipers}>
                                        <img src={item.room.thumb_text} alt="" />
                                    </div>
                                    <div className={styles.item_times}>
                                        <div>
                                            <div>{item.starttime_text}</div>
                                            <div>{item.startday_text}</div>
                                        </div>
                                        <div>
                                            <div>共{item.order_day}晚</div>
                                            <div className={styles.item_right}>
                                                <img src={require("@/assets/images/right1.png")} alt="" />
                                            </div>
                                        </div>
                                        <div>
                                            <div>{item.endtime_text}</div>
                                            <div>{item.endday_text}</div>
                                        </div>
                                        <div>
                                            <div className={styles.item_pay}>订单总价</div>
                                            <div className={styles.item_price}>￥{item.price}</div>
                                        </div>
                                    </div>
                                </div>

                                <div className={styles.item_bar}>
                                    {ButtonList(item)}    
                                
                                    <React.UI.Button color='primary' size='small' onClick={() => React.navigate(`/order/info?orderid=${item.id}`)}>查看详情</React.UI.Button>
                                </div>
                            </div>
                        ))}
                    </div>

                    {/* 上拉加载 */}
                    <React.UI.InfiniteScroll loadMore={LoadMore} hasMore={hasMore} threshold={0} />
                </React.UI.PullToRefresh>
            </div>

            {/* 评价弹框 */}
            <React.UI.Popup 
                visible={rateShow}
                bodyStyle={{height: '45vh', borderTopLeftRadius: '8px',borderTopRightRadius: '8px', paddingTop: '30px'}}
                closeOnMaskClick
                showCloseButton
                onClose={ClosePopup}
                onMaskClick={ClosePopup}
            >
                <React.UI.Form
                    form={form}
                    name="comment"
                    layout="horizontal"
                    mode="card"
                    initialValues={comment}
                    onFinish={Submit}
                    footer={<React.UI.Button block type='submit' color='primary' size='large'>提交</React.UI.Button>}
                >
                    <React.UI.Form.Item name="content" label="评价内容" rules={[{required: true, message: '请输入评价内容'}]}>
                        <React.UI.TextArea maxLength={100} rows={2} showCount placeholder="请输入评价内容" />
                    </React.UI.Form.Item>

                    <React.UI.Form.Item name="rate" label="评分" rules={[{required: true, message: '请选择评分'}]}>
                        <React.UI.Rate />
                    </React.UI.Form.Item>
                </React.UI.Form>
            </React.UI.Popup>

            <div className={styles.footer}>
                <Menu />
            </div>
        </>
    )
}